<template>
  <div class="comment-detail">
    <div class="comment-top">
      <div class="comment-user">
        <el-avatar size="large" :src="'/api/user/download/'+getUser(commentDetail.userId).avatarId"></el-avatar>
        <div>
          <a href="javascript:void(0)" @click="$router.push('/main/user/detail/'+commentDetail.userId)" class="comment-username" v-html="getUser(commentDetail.userId).username"></a>
          <el-link style="margin-left: 5px;" type="warning" v-if="updateAuth()" @click="$router.push('/main/comment/save?id='+commentDetail.id)">修改</el-link>
          <el-link style="margin-left: 5px;" type="danger" v-if="updateAuth()" @click="deleteClick(commentDetail)">删除</el-link>
          <br/>
          <span style="height: 55px;"></span>
          <br/>
          <span class="comment-updateTime">编辑于 {{commentDetail.updateTime}}</span>
        </div>
        <el-button v-show="$route.query.lurl" @click="$router.push($route.query.lurl)" style="margin-top:15px;margin-right:15px;float:right;background-color: #25bb9b;" type="info">返回全部帖子</el-button>

      </div>
      <h4 style="font-weight: 400;margin-left: 10px;">
       <i class="fa fa-header" style="color: #1daa1d"></i>&nbsp;&nbsp;&nbsp; {{commentDetail.title}}
      </h4>
      <hr/>
      <div>
        <mavonEditor :previewBackground="'#ffffff'" :ishljs = "true" :editable="false" :toolbarsFlag = "false" :defaultOpen="'preview'" :subfield="false"
         v-model="commentDetail.text" style="width: 100%;min-height: 20px;box-shadow: white 0 0 0 0;"/>

        <div style="margin-top: 10px;margin-bottom: 10px;">
          <a @click="likeSum(commentDetail)" href="javascript:void(0)" :style="'background-color: '+(isLike[commentDetail.id]?'#25bb9b':'#9f9f9f')+';border-radius: 4px;padding: 10px;vertical-align: middle;'">
            <i :class="isLike[commentDetail.id]?'fa fa-thumbs-up':'fa fa-thumbs-o-up'"></i> ({{commentDetail.likeSum}})
          </a>
          <span style="vertical-align: center;float: right"> 浏览 {{commentDetail.click}}</span>
        </div>
      </div>
    </div>
    <div class="comment-bottom">
      <div class="comment-header">
        <h4 style="margin-top: 10px;">全部评论 <span style="font-size: 12px;color: #999999;font-weight: 400">({{childrenTotal}}条)</span></h4>
        <el-radio-group v-model="childParams.fieldLabel" size="medium" style="margin-left: 20px;" @change="changField()">
          <el-radio-button label="like_sum" >最热</el-radio-button>
          <el-radio-button label="create_time" >最新</el-radio-button>
          <el-radio-button label="create_time_asc">楼层</el-radio-button>
        </el-radio-group>
      </div>
      <div class="comment-children">
        <div v-for="(item,itemIndex) in childrenList" :key="item.id" style="margin-top: 25px;">
          <div class="comment-user">
            <el-avatar size="large" :src="'/api/user/download/'+getUser(item.userId).avatarId"></el-avatar>
            <div>
              <a href="javascript:void(0)" @click="$router.push('/main/user/detail/'+item.userId)" class="comment-username" v-html="getUser(item.userId).username"></a>
              <span v-if="item.weight" style="color: #87ceeb;font-size: 12px;margin-left: 8px;">置顶</span>
              <br/>
              <span style="height: 55px;"></span>
              <br/>
          </div>

          </div>
          <div style="margin-left: 65px;margin-top: -40px;">
            <mavonEditor :previewBackground="'#ffffff'" :ishljs = "true" :editable="false" :toolbarsFlag = "false" :defaultOpen="'preview'" :subfield="false"
                         v-model="item.text" style="width: 100%;min-height: 20px;box-shadow: white 0 0 0 0;"/>

            <div style="float: right;" v-if="isLogin()">
              <el-link @click="likeSum(item)" :underline="false" style="color: #21a89a;font-size: 13px;margin-right: 10px;" ><i :class="isLike[item.id]?'fa fa-thumbs-up':'fa fa-thumbs-o-up'"></i> ({{item.likeSum}})</el-link>
              <el-link @click="replyClick(item,itemIndex)" :underline="false" style="color: #21a89a;font-size: 13px;margin-right: 10px;">回复({{item.total}})</el-link>
              <el-link v-show="updateAuth(item.userId)" @click="deleteClick(item)" :underline="false" v-if="item.status==0" style="font-size: 13px;margin-right: 10px;" type="danger">删除</el-link>
<!--              <el-link @click="setStatus(item,0)" :underline="false" v-if="item.status==1" style="font-size: 13px;margin-right: 10px;font-size: 13px;" >解禁</el-link>-->
            </div>
            <div class="comment-updateTime">发表于 {{item.createTime}}</div>
            <div class="comment-grandson" >
              <div  v-for="(child,index) in item.children" :key="child.id" v-show="index<=3||showChildren[itemIndex]">
                <div>
                  <a href="javascript:void(0)" @click="$router.push('/main/user/detail/'+child.userId)" style="color: #c177e8" v-html="getUser(child.userId).username"></a> :&nbsp; <span v-html="child.text"></span>
                </div>
                <div style="float: right;" v-if="isLogin()">
                  <el-link @click="likeSum(child)" :underline="false" style="color: #21a89a;font-size: 13px;margin-right: 10px;" >
                    <i :class="isLike[child.id]?'fa fa-thumbs-up':'fa fa-thumbs-o-up'"></i> ({{child.likeSum}})</el-link>
                  <el-link @click="replyClick(item,itemIndex,child)" :underline="false" style="color: #21a89a;font-size: 13px;margin-right: 10px;">回复</el-link>
                  <el-link v-show="updateAuth(child.userId)" @click="deleteClick(child)" :underline="false" v-if="child.status==0" style="font-size: 13px;margin-right: 10px;" type="danger">删除</el-link>

                  <!--                  <el-link @click="setStatus(child,0)" :underline="false" v-if="item.status==1" style="font-size: 13px;margin-right: 10px;font-size: 13px;" >解禁</el-link>-->
                </div>
                <div class="comment-updateTime">发表于 {{child.createTime}}</div>

                <hr style="margin-top: 12px;"/>

              </div>
              <el-button v-show="!showChildren[itemIndex]&&childrenList[itemIndex].total>3" type="info" size="mini" style="width:100%;background-color: #cfcfcf;margin-bottom: 10px;margin-top: 10px;" @click="$set(showChildren,itemIndex,true)">展 开</el-button>
              <el-pagination v-if="childrenList[itemIndex].total>10&&showChildren[itemIndex]"
                             background
                             layout="prev, pager, next"
                             :total="childrenList[itemIndex].total"
                             :page-size="10"
                             @current-change="(val) => chgSon(itemIndex,val)" style="text-align: center">
              </el-pagination>
              <div style="overflow: hidden;margin-top: 10px;" v-show="replyFlag[itemIndex]">
                <el-input autosize type="textarea"  v-model="replyText.text" :placeholder="replyPlaceholder"></el-input>
                <el-button @click="submitReply(itemIndex)" size="medium" style="background-color: #25bb9b;color: white;float: right;margin-top: 10px;">回复</el-button>
              </div>
            </div>

          </div>


        </div>
        <!--分页-->
        <hr/>
        <div style="margin-top: 20px;">
          <el-pagination style="text-align: center"
              background
              layout="prev, pager, next"
              :total="childrenTotal"
              :page-size="childParams.size"
              :page-sizes="[10,20,30,50,100]"
              @current-change="chg"
              @size-change="chgsize"
          >
          </el-pagination>

        </div>
      </div>
    </div>
    <div v-show="true" style="" class="comment-reply">
      <mavonEditor :toolbarsFlag = "true"
                   :subfield = 'false'
                   ref="md"
                   v-model="detailReply.text"
                   v-bind="$attrs"
                   v-on="$listeners"
                   @imgAdd="handleImgAdd"
                   style="min-height: 80px;width: 100%;"/>
      <el-button @click="submitReply(-1)" size="medium" style="background-color: #bbbbbb;color: white;float: right;margin-top: 10px;margin-right: 10px;">回帖</el-button>

    </div>
  </div>
</template>

<script>
import * as commentApi from '@/api/comment'
import {getEasyUserById, uploadImage} from '@/api/admin'
import { mavonEditor } from 'mavon-editor';
import 'mavon-editor/dist/css/index.css';
import {isRoot,isLogin,loginUser,removeToken,isAdmin} from '@/utils/auth'
export default {
  name: "commentDetail",
  data() {
    return {
      detailReply:{
        fatherId:this.$route.params.id,
        type:1,
      },
      replyFlag:[], //回复弹窗
      replyText: {

      },//评论回复内容
      replyPlaceholder:'请输入你的观点',
      commentDetail:{},
      userNames:{},
      isLike:{},
      //其评论列表
      childrenList:[],
      childrenTotal:0,
      childParams:{
        page:1,
        size:10,
        fieldLabel:'create_time',
        type:'1',
      },
      grandSonParams:[],
      showChildren:[], //子页面是否展开
    }
  },
  components: {
    mavonEditor,   //markdown编译器
  },
  methods: {
    likeSum(item){  //点赞或取消点赞
      commentApi.clickCommentLikeByCommentId({"commentId":item.id}).then(res=>{
        if(res.data.success){

          this.isLike[item.id+''] = !this.isLike[item.id+''];
          if(this.isLike[item.id+'']){
            this.$message({"type":"success",message:"点赞成功"})
            item.likeSum +=1;
          }else {
            item.likeSum -=1;
            this.$message("已取消")
          }
          // console.info(this.isLike);
          this.isLike = JSON.parse(JSON.stringify(this.isLike));

        }
      })
    },
    getLikeUser(id){  //获取用户点赞情况
      commentApi.getCommentLikeByCommentId({"commentId":id}).then(res=>{
        if(res.data.data){
          this.isLike[id] = true;
        }else this.isLike[id] = false;
        // this.isLike = JSON.parse(JSON.stringify(this.isLike));
      })
    },
    deleteClick(item){ //删除
      this.$confirm('此操作将永久删除 '+this.getUser(item.userId).username +' 发布的内容, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        commentApi.deleteComment({"id":item.id}).then(res=>{
          if(res.data.success){
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            if(item.type==0){
              this.$router.go(-1);
            }else{
              this.getcommentList();
            }
          }
        })
      })
    },
    updateAuth(id){ //操作权限，帖子发布者，评论发布者，管理员
      if(isAdmin())return true;
      var userId = loginUser().id;
      // console.info(userId,id,this.commentDetail.userId)
      if(userId==id||userId==this.commentDetail.userId)return true;
      return false;
    },
    //每页记录数发生改变时
    chgsize(pgsize) {
      //更改每页记录数
      this.childParams.size = pgsize;
      //从每一页开始查询
      this.childParams.page = 1;
      //重新查询
      this.getcommentList();
    },
    //当页数发生变化时执行
    chg(curpage) {
      //更新查询的页数
      this.childParams.page = curpage;
      //重新查询
      this.getcommentList();
    },
    //当二级评论页数发生变化时执行
    chgSon(index,curpage) {
      //更新查询的页数
      this.grandSonParams[index].page = curpage;
      //重新查询
      this.getChildCommentList(index)
    },
    submitReply(index,itemIndex){   //发表评论
      if(this.replyText.type==2){//二级评论
        this.replyText.text = "<span style='color: #c177e7;'>"+this.replyPlaceholder+" </span>" + this.replyText.text;
      }
      if(index!=-1) {
        this.replyText.type = 2;
      }else{//表示直接评论,一级评论
        this.replyText = this.detailReply;
        this.replyText.title = this.commentDetail.userId;  //title 存储userId
      }
      commentApi.saveComment(this.replyText).then(res=>{
        if(res.data.success){
          if(itemIndex>=0)this.$set(this.replyFlag,itemIndex,false);//关闭输入框
          this.replyFlag = {};
          // this.replyFlag = !this.replyFlag;
          this.replyText.text = ''; //清空内容
          this.$message({type:"success",message:"回复成功"});
          if(index>=0)this.getChildCommentList(index);
          else if(index==-1) this.getcommentList();
        }
      })
    },
    replyClick(item,itemIndex,child){  //回复弹出框
      this.replyText.fatherId = item.id;
      // 回复弹窗
      if(child){//二级评论
        this.replyText.type = 2;
        this.replyPlaceholder = '@'+this.getUser(child.userId).username;
        this.replyText.title = child.userId;
      }else{//二级评论 回复楼主
        this.replyText.type = 1; //接下来重新赋值为 2
        this.replyPlaceholder = '请输入你的观点';
        this.replyText.title = item.userId;
      }
      this.$set(this.replyFlag,itemIndex,!this.replyFlag[itemIndex]);//关闭输入框
    },
    isLogin(){
      return isLogin();
    },
    changField(){//筛选
      // console.info(this.childParams)
      this.childParams.field = this.childParams.fieldLabel;
      this.childParams.order = 'desc'; //其他为倒序
      if(this.childParams.fieldLabel=='create_time_asc'){  //升序
        this.childParams.field = 'create_time';
        this.childParams.order = 'asc';
      }
      this.getcommentList();
    },
    getCommentDetail(id){
      commentApi.getCommentDetail({"id":id}).then(res=>{
        if(res.data.data){
          getEasyUserById({"id":res.data.data.userId}).then(res2=>{
            if(res2.data.data){
              this.userNames[res2.data.data.id] =   res2.data.data;
            }
            this.commentDetail = res.data.data;
          })


        }
      })
      //获取其子评论列表
      this.getcommentList();

    },
    getUser(userId){
      if(!this.userNames[userId]){
        this.userNames[userId] = {};
        this.userNames[userId].username =  '<span style="color:grey">未知用户</span>';
      }
      return this.userNames[userId];
    },
    //负责获取其子评论列表
    getcommentList(){
      commentApi.commentListSearch(this.childParams).then(async res=>{
        if(res.data.data){
          var tables = res.data.data.dataList;
          //获取用户名字
          for(var i = 0;i<tables.length;i++){
            // console.info(tables[i].userId)
            this.getLikeUser(tables[i].id); //获取其点赞情况
            if(!this.userNames[tables[i].userId]){

              await getEasyUserById({"id":tables[i].userId}).then(res2=>{
                if(res2.data.data&&res2.data.data.username){
                  // console.info("success="+res2.data.data.id);
                  this.userNames[res2.data.data.id] =   res2.data.data;
                }else{
                  this.userNames[tables[i].userId].username =  '<span style="color:grey">未知用户</span>';
                }
              });
            }
          }
          this.childrenList = tables;
          for(i = 0;i<tables.length;i++){
            this.grandSonParams[i] = {"type":2,"fatherId":tables[i].id,"order":"asc"}
            this.getChildCommentList(i,this.grandSonParams[i]);
          }

          this.childrenTotal = res.data.data.total;
        }
      })

    },
    //孙子评论
    getChildCommentList(index,params){
      commentApi.commentListSearch(params?params:this.grandSonParams[index]).then(async res=>{
        if(res.data.data){
          var tables = res.data.data.dataList;
          //获取用户名字
          for(var i = 0;i<tables.length;i++){
            // console.info(tables[i].userId)\
            //this.getLikeUser(tables[i].id); //获取其点赞情况
            await commentApi.getCommentLikeByCommentId({"commentId":tables[i].id}).then(res1=>{
              if(res1.data.data){
                this.isLike[tables[i].id] = true;
              }else this.isLike[tables[i].id] = false;
              // this.isLike = JSON.parse(JSON.stringify(this.isLike));
            })
            if(!this.userNames[tables[i].userId]){

              // await commentApi.getCommentLikeByCommentId({"commentId":tables[i].id}).then(res1=>{
              //   if(res1.data.data){
              //     this.isLike[tables[i].id] = true;
              //   }else this.isLike[tables[i].id] = false;
              //   // this.isLike = JSON.parse(JSON.stringify(this.isLike));
              // })
              await getEasyUserById({"id":tables[i].userId}).then(res2=>{
                if(res2.data.data&&res2.data.data.username){
                  // console.info("success="+res2.data.data.id);
                  this.userNames[res2.data.data.id] =   res2.data.data;
                }else{
                  this.userNames[tables[i].userId].username =  '<span style="color:grey">未知用户</span>';
                }
              });
            }
          }
          this.childrenList[index].children = tables;
          this.childrenList[index].total = res.data.data.total;
          // this.childrenList =
          this.$set(this.childrenList,index,JSON.parse(JSON.stringify(this.childrenList[index])))
          // this.childrenTotal = res.data.data.total;
        }
      })


    },
    // 将图片上传到服务器，返回地址替换到md中
    async handleImgAdd(pos, file) {
      let form = new FormData();
      form.append('file', file);

      const res = await uploadImage(form).then(res=>{
        return '/api/user/download/'+res.data.data;
      })
      console.log(res);
      this.$refs.md.$img2Url(pos, res);
    },

  },
  created() {

    console.info(this.$route.query.lurl)
    this.childParams.fatherId = this.$route.params.id;
    this.getCommentDetail(this.$route.params.id);
    this.getLikeUser(this.$route.params.id);  //获取其 id 的点赞情况
  }
}
</script>

<style scoped>
.comment-detail{
  width: 1000px;
  margin: 0 auto;
}
.comment-detail .comment-top{
  text-align: left;
  box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
  background-color: white;
  vertical-align: top;
  padding: 10px;

}
.comment-detail  .comment-user > div{
  display: inline-block;
  vertical-align: top;
}
.comment-detail  .comment-username{
  vertical-align: top;
  color: #c177e7;
  margin-left: 10px;

}
.comment-detail  .comment-updateTime{
  color: grey;
  font-size: 12px;
  margin-left: 10px;
  vertical-align: bottom;
  margin-top: 10px;
}


.comment-detail .comment-bottom{
  margin-top: 20px;
  text-align: left;
  box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
  background-color: white;
  /*vertical-align: top;*/
  padding: 10px;

}
.comment-detail .comment-bottom .comment-header *{
  display: inline-block;
}
.comment-detail .comment-bottom .comment-grandson{
  border-radius: 4px;
  background-color: #eff0f2;
  margin-top: 12px;
  padding: 10px;
  font-size: 90%;
}


.comment-detail .comment-reply{
  overflow: hidden;
  background-color: white;
  margin-top: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
  /*padding: 10px;*/
  padding-bottom: 10px;
}
</style>
<style>
.comment-detail  .el-avatar--large{
  width: 64px;
  height: 64px;
}

</style>
